package cn.unknowpupil.executor.task;

import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.NoSuchPortException;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.UnsupportedCommOperationException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Enumeration;

/**
 * Create at  2021/8/31 by w10g <br>
 * Initialize SerialPortManager ... <br>
 *
 * @Author: <a> unknowpupil </a>
 * @Since: 0.0.1
 */

@SuppressWarnings("all")
public class SerialPortManager {

    /**
     * 查找所有可用端口
     *
     * @return 可用端口名称列表
     */
    public static final ArrayList<String> findPorts() {
        // 获得当前所有可用串口
        Enumeration<CommPortIdentifier> portList = CommPortIdentifier.getPortIdentifiers();
        ArrayList<String> portNameList = new ArrayList<String>();
        // 将可用串口名添加到List并返回该List
        while (portList.hasMoreElements()) {
            String portName = portList.nextElement().getName();
            portNameList.add(portName);
        }
        return portNameList;
    }


    /**
     * 打开串口
     *
     * @param portName 端口名称
     * @param baudrate 波特率
     * @return 串口对象
     * @throws PortInUseException 串口已被占用
     */
    public static final SerialPort openPort(String portName, int baudrate) throws PortInUseException {
        try {
            // 通过端口名识别端口
            CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
            // 打开端口，并给端口名字和一个timeout（打开操作的超时时间）
            CommPort commPort = portIdentifier.open(portName, 2000);
            // 判断是不是串口
            if (commPort instanceof SerialPort) {
                SerialPort serialPort = (SerialPort) commPort;
                try {
                    // 设置一下串口的波特率等参数
                    // 数据位：8
                    // 停止位：1
                    // 校验位：None
                    serialPort.setSerialPortParams(baudrate, SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
                            SerialPort.PARITY_NONE);
                } catch (UnsupportedCommOperationException e) {
                    e.printStackTrace();
                }
                return serialPort;
            }
        } catch (NoSuchPortException e1) {
            e1.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) throws PortInUseException {
        String s = "0012 你好我在测试 +1";
        String s2 = SBH.string2HexGBK(s);
        SerialPort com3_usb_serial_port = openPort("COM3", 115200);
        System.out.println(com3_usb_serial_port);

        String data = "AT+SENDSMS=13577131953,," + s2;

        SerialPortManager.sendToPort(com3_usb_serial_port, data.getBytes());
//        String s = "我是一个兵";
//        String s2 = SBH.string2HexGBK(s);

//        String s1 = string2HexGBK(s);
        System.out.println(s2);

        String s1 = SBH.hexGBK2String(s2);
        System.out.println(s1);
//        System.out.println(toChineseHex("B6A8CAB1A3BAC1F7C1BFBCE0B2E2D5BE5B323032313037303530315DCBB2CAB1C1F7C1BFA3BA31332E36393920B2C9BCAFCAB1BCE4A3BA323032312D30372D32332032323A3330"));
//        System.out.println(toStringHex2("B6A8CAB1A3BAC1F7C1BFBCE0B2E2D5BE5B323032313037303530315DCBB2CAB1C1F7C1BFA3BA31332E36393920B2C9BCAFCAB1BCE4A3BA323032312D30372D32332032323A3330"));

//        System.out.println(s);
    }

    /**
     * @param strPart 字符串
     * @return 16进制字符串
     * @throws
     * @Title:string2HexGBK
     * @Description:字符GBK串转16进制字符串
     */
    public static String string2HexGBK(String strPart) {

        return string2HexString(strPart, "GBK");
    }

    public static String string2HexString(String strPart, String tochartype) {
        try {
            return SBH.bytes2HexString(strPart.getBytes(tochartype));
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * @param src 16进制字符串
     * @return 字节数组
     * @throws
     * @Title:hexGBK2String
     * @Description:16进制GBK字符串转字符串
     */
    public static String hexGBK2String(String src) {

        return SBH.hexString2String(src, "GBK", "UTF-8");
    }

    public static String toHexString(String s) {
        String str = "";

        for (int i = 0; i < s.length(); i++) {
            int ch = (int) s.charAt(i);

            String s4 = Integer.toHexString(ch);

            str = str + s4;

        }
        return str;
    }

    public static String toChineseHex(String s) {
        String ss = s;
        byte[] bt = ss.getBytes();
        String s1 = "";
        for (int i = 0; i < bt.length; i++) {
            String tempStr = Integer.toHexString(bt[i]);
            if (tempStr.length() > 2)
                tempStr = tempStr.substring(tempStr.length() - 2);
            s1 = s1 + tempStr + " ";
        }
        return s1.toUpperCase();
    }

    public static String toStringHex2(String s) {
        byte[] baKeyword = new byte[s.length() / 2];
        for (int i = 0; i < baKeyword.length; i++) {
            try {
                baKeyword[i] = (byte) (0xff & Integer.parseInt(s.substring(
                        i * 2, i * 2 + 2), 16));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        try {
            s = new String(baKeyword, "gbk");// UTF-16le:Not
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return s;
    }

    /**
     * 往串口发送数据
     *
     * @param serialPort 串口对象
     * @param order      待发送数据
     */
    public static void sendToPort(SerialPort serialPort, byte[] order) {
        OutputStream out = null;
        try {
            out = serialPort.getOutputStream();
            out.write(order);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                    out = null;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


}
